#include "NotificationCenter.h"

NS_CC_CORE_BEGIN

static NotificationCenter*	s_sharedNotificationCenter = NULL;


NotificationCenter* NotificationCenter::sharedNotificationCenter( )
{
	if( s_sharedNotificationCenter == NULL )
	{
		s_sharedNotificationCenter = new NotificationCenter( );
	}

	return s_sharedNotificationCenter;
}



NotificationCenter::NotificationCenter( )
{
	m_pListHandler = LStaticArray<NotificationDelegate>::create();
}

NotificationCenter::~NotificationCenter( )
{
	int size = m_pListHandler->count( );

	for( int i = m_pListHandler->begin() ; i < m_pListHandler->end() ; i = m_pListHandler->next() )
	{
		unregisterHandlerMessage( m_pListHandler->getObject(i) );
	}

	CC_SAFE_DELETE(m_pListHandler);
}


void NotificationCenter::registerHandlerMessage( NotificationDelegate* pHandler )
{
	m_pListHandler->addObject( pHandler );
}

void NotificationCenter::unregisterHandlerMessage( NotificationDelegate* pHandler , bool onRelease )
{
	if( m_pListHandler )
		m_pListHandler->removeObject(pHandler , onRelease);
}


void NotificationCenter::post(NotificationData* data , int messageId , int messageSubId /*= 0*/)
{
	int size = m_pListHandler->count( );

	for( int i = m_pListHandler->begin() ; i < m_pListHandler->end() ; i = m_pListHandler->next() )
	{
		m_pListHandler->getObject(i)->onHandlerMessage( data , messageId , messageSubId );
	}
}



void NotificationCenter::post( int messageId , int messageSubId /*= 0*/)
{
	post( NULL , messageId , messageSubId );
}


void NotificationCenter::purge( )
{
	CC_SAFE_DELETE(s_sharedNotificationCenter);
}



//---------------Notification Node class implement-----------------//
NotificationNode::NotificationNode( )
{
	NotificationCenter::sharedNotificationCenter()->registerHandlerMessage(this);
}


NotificationNode::~NotificationNode( )
{
	NotificationCenter::sharedNotificationCenter()->unregisterHandlerMessage(this);
}

NS_CC_CORE_END